package com.pf.schedule;

import com.pf.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 定时任务
 *
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/8/10
 */
@Component
@Slf4j
public class ScheduledTask {

    @Value("${server.port}")
    private Integer serverPort;

    /**
     * 每十秒执行一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void executeTask() {
        // 设置redis锁，过期时间3秒。等同于redis setnx(key,value)
        boolean flag = RedisUtils.setIfAbsent("executeTask", UUID.randomUUID().toString(), 3);
        // flag为true，则说明已获取到redis锁
        if (flag) {
            // 执行业务逻辑
            log.info(">>>>> 端口；{} -> ScheduledTask executeTask run......", serverPort);
        }
    }
}
